<template>
  <div class="detail-container">
    <!-- 顶部导航 -->
    <div class="detail-header">
      <div class="header-nav">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">详情</div>
      </div>
    </div>
    
    <!-- 渐变背景区域 -->
    <div class="gradient-section">
      <!-- 文本信息区域 -->
      <div class="text-container">
        <div class="header-title" v-if="detailData.createName">
          {{ detailData.createName }}提交的付款审批
        </div>
        <div class="company—title">北京君初律师事务所</div>
        <div class="company-handle" :class="getStatusClass()">
          {{ getHandleText() }}
        </div>
      </div>
      <!-- 页面图标和状态图标 -->
      <div class="icon-container">
        <div class="main-icon">
          <img src="@/assets/homeOther/reimburse_page_icon.png" alt="详情图标" class="icon-img" />
          <!-- 状态图标 -->
          <div class="status-badge" v-if="getStatusIcon()">
            <img :src="getStatusIcon()" :alt="getStatusText()" class="status-img" />
          </div>
        </div>
      </div>
    </div>

    <!-- 详情内容 -->
    <div class="detail-content">

      <!-- 基本信息 -->
      <div class="info-section">
        <div class="section-title">基本信息</div>
        <div class="info-list">
          <div class="info-item">
            <div class="info-label">申请编号</div>
            <div class="info-value">{{ detailData.no || detailData.id }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">申请人</div>
            <div class="info-value">{{ detailData.name }}</div>
          </div>
          <!-- 附件 -->
            <div class="info-item"  v-if="detailFileList.length">
            <div class="info-label">付款附件</div>
            <div class="info-value">  <VantUploader v-model="detailFileList" :showUploadButton="false" :deletable="false" :readonly="true" /></div>
          </div>
          <div class="info-item">
            <div class="info-label">申请时间</div>
            <div class="info-value">{{ detailData.createDate ? formatDateOnly(detailData.createDate) : '' }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">部门</div>
            <div class="info-value">{{ detailData.department }}</div>
          </div>
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="detail-section">
        <div class="section-title">付款详情</div>
        <div class="detail-list">
          <div class="detail-item" v-if="detailData.payAmount">
            <div class="detail-label">付款金额</div>
            <div class="detail-value amount">¥{{ detailData.payAmount.toFixed(2) }}</div>
          </div>
          <div class="detail-item" v-if="detailData.payDate">
            <div class="detail-label">付款日期</div>
            <div class="detail-value">{{ formatDateUTCLine(detailData.payDate) }}</div>
          </div>
          <div class="detail-item" v-if="detailData.payObjectName">
            <div class="detail-label">付款对象</div>
            <div class="detail-value">{{ detailData.payObjectName}}</div>
          </div>
          <div class="detail-item" v-if="detailData.payRemark">
            <div class="detail-label">付款说明</div>
            <div class="detail-value">{{ detailData.payRemark }}</div>
          </div>
        </div>
      </div>

      <!-- 审批流程 -->
      <div class="approval-section">
        <div class="section-title">流程</div>
        <div class="approval-list">
          <div 
            v-for="(step, index) in detailData.approvalSteps || []" 
            :key="index"
            class="approval-step"
            :class="{ 'current': step.isCurrent, 'completed': step.isCompleted }"
          >
            <!-- 左侧：头像和审批信息 -->
            <div class="step-left">
              <div class="step-avatar">
                <AvatarDisplay :url="step.avatarUrl" :name="step.userName" />
                <!-- 状态图标 -->
                <div class="step-status" v-if="step.isCompleted || step.isCurrent">
                <van-icon 
                  :name="step.isCompleted ? 'success' : 'ellipsis'" 
                  :color="step.isCompleted ? '#FFFFFF' : '#FFFFFF'"
                  :style="{
                    backgroundColor: step.isCompleted ? '#4CAF50' : '#FF9200',
                    borderRadius: '50%',
                    padding: '2px',
                    width: '16px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }"
                  size="10px"
                />
                </div>
              </div>
              <div class="step-info">
                <div class="step-title">{{ step.title }}</div>
                <div class="step-user">{{ step.user }}</div>
              </div>
            </div>
            <!-- 右侧：时间 -->
            <div class="step-right">
              <div class="step-time" v-if="step.time">{{ step.time }}</div>
            </div>
            <!-- 连接线 -->
            <div class="step-line" v-if="index < (detailData.approvalSteps || []).length - 1"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div 
      class="action-buttons" 
      v-if="
        (shouldShowRevokeButton() &&
          detailData.firstApproverState == 0 &&
          detailData.secondApproverState == 0 &&
          detailData.nowState === 0) ||
        shouldShowApprovalButtons()
      "
    >
      <van-button 
        v-if="
          shouldShowRevokeButton() &&
          detailData.firstApproverState == 0 &&
          detailData.secondApproverState == 0 &&
          detailData.nowState === 0
        "
        class="action-btn revoke-btn" 
        @click="showRevokeDialog"
        :loading="revokeLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!revokeLoading" name="revoke" class="btn-icon" />
        撤销
      </van-button>
      <van-button 
        v-if="shouldShowApprovalButtons()"
        class="action-btn reject-btn" 
        @click="showRejectDialog"
        :loading="rejectLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!rejectLoading" name="close" class="btn-icon" />
        拒绝
      </van-button>
      <van-button 
        v-if="shouldShowApprovalButtons()"
        class="action-btn approve-btn" 
        @click="showApproveDialog"
        :loading="approveLoading"
        :disabled="revokeLoading || approveLoading || rejectLoading"
        plain
      >
        <van-icon v-if="!approveLoading" name="success" class="btn-icon" />
        同意
      </van-button>
    </div>

    <!-- 通用确认弹窗 -->
    <van-dialog 
      v-model:show="showConfirmDialog" 
      show-cancel-button
      :confirm-button-text="dialogConfig.confirmText"
      cancel-button-text="取消"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <div class="dialog-content">
        <div class="dialog-text">{{ dialogConfig.message }}</div>
        <van-field
          v-model="remark"
          type="textarea"
          :placeholder="dialogConfig.placeholder"
          rows="3"
          maxlength="200"
          show-word-limit
          required
        />
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showImagePreview } from 'vant'
import { queryDetailApi, dealPayApi } from '@/api/home'
import { getUserPicture ,revokeContract} from '@/api/contract'
import { formatShortDateTime,formatDateUTCLine ,formatDateOnly} from '@/utils/formatters'
import isolatedStorage from '@/utils/storage'
import pictureImg from "@/assets/homeOther/picture.png";
import pictureOneImg from "@/assets/homeOther/sm_picture.png";
import pictureTwoImg from "@/assets/homeOther/picture_two.png";
// 导入默认头像
import defaultAvatar from '@/assets/homeOther/default_avatar.svg'
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue'
import VantUploader from '@/components/UploadFiled/VantUploader.vue'
import { request, API_BASE_URL } from '@/utils/http'
import { getDetailBackTarget, useSmartDetailBack } from '@/utils/navigation'
import { refreshTokenApi } from '@/api/index'

// 路由实例
const router = useRouter()
const route = useRoute()

// 启用智能返回：根据来源(home/approvals/add)处理左滑/系统返回
useSmartDetailBack(router, route)

// 详情数据类型定义
interface ApprovalStep {
  title: string
  user: string
  userName: string // 用户名用于头像组件
  time?: string
  avatar?: any
  avatarUrl?: string // 头像URL用于头像组件
  isCurrent: boolean
  isCompleted: boolean
}

interface DetailData {
  id: string
  name: string
  createDate: string | null
  createId: number
  no?: string | null
  department: string
  
  // 审批相关字段
  firstApprover: number
  secondApprover: number
  thirdApprover: number
  nowApprover: number
  nowState?: number
  firstApproverState: number
  secondApproverState: number
  thirdApproverState: number
  approveDate?: string | null
  
  // 审批人头像URL字段
  firstApproverUrl?: string | null
  secondApproverUrl?: string | null
  thirdApproverUrl?: string | null
  
  // 新增字段
  createName?: string | null
  createUrl?: string | null
  firstApproverName?: string | null
  secondApproverName?: string | null
  thirdApproverName?: string | null
  
  // 付款特有字段
  payAmount?: number | null
  payDate?: string | null
  payRemark?: string | null
  payObject?: string | null
  payObjectName?: string | null
  // 前端显示用字段
  status?: 'revoked' | 'passed' | 'rejected'
  approvalSteps?: ApprovalStep[]
}

// 加载状态
const loading = ref(false)
const revokeLoading = ref(false)
const approveLoading = ref(false)
const rejectLoading = ref(false)

// 通用弹窗状态
const showConfirmDialog = ref(false)
const remark = ref('')
const currentAction = ref<'revoke' | 'reject' | 'approve'>('approve')

// 弹窗配置
const dialogConfig = ref({
  title: '',
  message: '',
  confirmText: '',
  placeholder: ''
})

// 当前登录用户ID
const currentUserId = ref<number | null>(null)

// 详情数据
const detailData = reactive<DetailData>({
  id: '',
  name: '',
  createDate: null,
  createId: 0,
  no: null,
  department: '',
  firstApprover: 0,
  secondApprover: 0,
  thirdApprover: 0,
  nowApprover: 0,
  nowState: 0,
  firstApproverState: 0,
  secondApproverState: 0,
  thirdApproverState: 0,
  approveDate: null,
  payAmount: null,
  payDate: null,
  payRemark: null,
  payObject: null,
  payObjectName: null,
  status: 'passed',
  approvalSteps: []
})

// 获取状态图标
const getStatusIcon = () => {
  // 根据当前审批状态判断 nowState: 0是等待审批 1是审批完成 -1是已撤销 2是已拒绝
  if (detailData.nowState === 0) {
    // 0是等待审批-没有图标
    return ''
  } else if (detailData.nowState === 1) {
    // 1是审批完成
    return '/src/assets/homeOther/passed.png'
  } else if (detailData.nowState === -1) {
    // -1是已撤销
    return '/src/assets/homeOther/revoked_iocn.png'
  } else if (detailData.nowState === 2) {
    // 2是已拒绝
    return '/src/assets/homeOther/rejected.png'
  }
  return ''
}

// 获取状态文本
const getStatusText = () => {
  const nowState = detailData.nowState || 0
  
  if (nowState === 0) {
    return '等待审批'
  } else if (nowState === 1) {
    return '已通过'
  } else if (nowState === -1) {
    return '已撤销'
  } else if (nowState === 2) {
    return '已拒绝'
  }
  return '等待审批'
}

// 获取状态样式类
const getStatusClass = () => {
  const nowState = detailData.nowState || 0
  
  switch (nowState) {
    case 0:
      return 'status-pending' // 等待审批
    case 1:
      return 'status-completed' // 审批完成
    case -1:
      return 'status-revoked' // 已撤销
    case 2:
      return 'status-rejected' // 已拒绝
    default:
      return 'status-pending' // 默认等待审批
  }
}

// 获取处理状态文本
const getHandleText = () => {
  const nowState = detailData.nowState || 0
  
  if (nowState === 0) {
    // 等待审批状态，根据当前审批人ID匹配姓名
    const nowApprover = detailData.nowApprover
    let approverName = ''
    
    if (nowApprover === detailData.firstApprover) {
      approverName = detailData.firstApproverName || ''
    } else if (nowApprover === detailData.secondApprover) {
      approverName = detailData.secondApproverName || ''
    } else if (nowApprover === detailData.thirdApprover) {
      approverName = detailData.thirdApproverName || ''
    }
    
    return approverName ? `等待${approverName}处理` : '等待处理'
  } else if (nowState === 1) {
    return '审批完成'
  } else if (nowState === -1) {
    return '已撤销'
  } else if (nowState === 2) {
    return '审批拒绝'
  }
  return '等待处理'
}

// 获取付款对象名称
const getPayObjectName = (payObject: string) => {
  const payObjectMap: { [key: string]: string } = {
    '1': '供应商',
    '2': '员工',
    '3': '其他'
  }
  return payObjectMap[payObject] || payObject
}

// 返回：根据来源(home/approvals/add)智能跳转
const goBack = () => {
  const target = getDetailBackTarget(route)
  router.push(target)
}

// 加载用户头像
const loadUserAvatar = async (url: string) => {
  if (!url) return defaultAvatar
  
  try {
    const blob = await getUserPicture(url)
    return URL.createObjectURL(blob)
  } catch (error) {
    console.error('加载头像失败:', error)
    return defaultAvatar
  }
}

// 获取用户头像URL
const getAvatarUrl = (user: string) => {
  // 这里可以根据用户信息生成头像URL，或者从用户信息中获取
  // 目前使用默认头像
  return defaultAvatar
}

// 获取详情数据
const fetchDetailData = async () => {
  const id = route.params.id as string
  const type = route.query.type as string
  
  if (!id || !type) {
    showToast('页面参数错误，请重新进入')
    setTimeout(() => {
      router.push('/contract')
    }, 1500)
    return
  }
  
  try {
    loading.value = true
    const response = await queryDetailApi(id, type)
    
    console.log('API响应数据:', response)
    
    if (response.code === 0) {
      console.log('原始detailData:', JSON.stringify(detailData))
      console.log('API返回的data:', response.data)
      
      // 更新详情数据
      Object.assign(detailData, response.data)
      
      console.log('更新后的detailData:', JSON.stringify(detailData))
      console.log('payObject值:', detailData.payObject)
      
      // 构建审批流程数据
      await buildApprovalSteps()
      
      // showToast('数据加载完成')
    } else {
      showToast(response.msg || '数据加载失败')
    }
  } catch (error) {
    showToast('数据加载失败')
    console.error('获取详情数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 构建审批流程数据
const buildApprovalSteps = async () => {
  const steps: ApprovalStep[] = []
  const nowState = detailData.nowState || 0

  // 发起申请步骤
  const createAvatar = detailData.createUrl
    ? await loadUserAvatar(detailData.createUrl)
    : pictureImg

  // 添加发起申请步骤
  steps.push({
    title: "发起申请",
    user: `申请人: ${detailData.createName || detailData.name}`,
    userName: detailData.createName || detailData.name || "",
    time: detailData.createDate ? formatShortDateTime(detailData.createDate) : "",
    avatar: createAvatar,
    avatarUrl: detailData.createUrl || "",
    isCurrent: false,
    isCompleted: true,
  })

  // 如果是已撤销状态，添加撤销步骤，不显示审批人
  if (nowState === -1) {
    steps.push({
      title: "已撤销",
      user: `${detailData.createName || detailData.name} (已撤销)`,
      userName: detailData.createName || detailData.name || "",
      time: "", // 撤销时间可以根据实际需求添加
      avatar: createAvatar,
      avatarUrl: detailData.createUrl || "",
      isCurrent: false,
      isCompleted: false,
    })
    detailData.approvalSteps = steps
    return
  }

  // 获取审批状态文本
  const getApprovalStatusText = (state: number) => {
    switch (state) {
      case 0:
        return "未审批"
      case 1:
        return "已审批"
      case -1:
        return "已拒绝"
      default:
        return "未审批"
    }
  }

  // 审批人信息数组，包含所有可能的审批人
  const approvers = [
    {
      id: detailData.firstApprover,
      name: detailData.firstApproverName,
      url: detailData.firstApproverUrl,
      state: detailData.firstApproverState,
      defaultAvatar: pictureOneImg,
    },
    {
      id: detailData.secondApprover,
      name: detailData.secondApproverName,
      url: detailData.secondApproverUrl,
      state: detailData.secondApproverState,
      defaultAvatar: pictureTwoImg,
    },
    {
      id: detailData.thirdApprover,
      name: detailData.thirdApproverName,
      url: detailData.thirdApproverUrl,
      state: detailData.thirdApproverState,
      defaultAvatar: defaultAvatar,
    },
  ]

  // 遍历审批人，实现流程中断逻辑
  let shouldStop = false
  for (const approver of approvers) {
    // 如果已经遇到失败步骤，后续步骤都不显示
    if (shouldStop) break

    // 只显示有效的审批人（ID存在且不为-1）
    if (approver.id && approver.id !== -1) {
      const avatar = approver.url
        ? await loadUserAvatar(approver.url)
        : approver.defaultAvatar
      const statusText = getApprovalStatusText(approver.state)

      steps.push({
        title: "审批人",
        user: `${approver.name || ""} (${statusText})`,
        userName: approver.name || "",
        // time:
        //   approver.state === 1 && detailData.approveDate
        //     ? formatShortDateTime(detailData.approveDate)
        //     : "",
        time:"",
        avatar: avatar,
        avatarUrl: approver.url || "",
        isCurrent:
          approver.state === 0 && detailData.nowApprover === approver.id,
        isCompleted: approver.state === 1,
      })

      // 如果当前审批人已拒绝，标记需要停止后续步骤
      if (approver.state === -1) {
        shouldStop = true
      }
    }
  }

  detailData.approvalSteps = steps
}

// ================= 附件解析与预览 =================
const attachmentList = computed(() => {
  const raw = (detailData as any).attachmentUrl || ''
  if (!raw || typeof raw !== 'string') return [] as Array<{ path: string; name: string; ext: string }>
  return raw
    .split(',')
    .map((s: string) => s.trim())
    .filter((s: string) => !!s)
    .map((path: string) => {
      const normalized = path.replace(/\\/g, '/');
      const name = normalized.split('/').pop() || '附件';
      const lower = (name || '').toLowerCase();
      const ext = lower.includes('.') ? lower.split('.').pop() || '' : '';
      return { path: normalized, name, ext };
    })
})

const detailFileList = ref<Array<any>>([])
watch(
  attachmentList,
  (list) => {
    const imgExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    detailFileList.value = (list || []).map((att, idx) => {
      const ext = (att.name || att.path || '').toLowerCase().split('.').pop() || ''
      const isImg = imgExts.includes(ext)
      const path = att.path
      const isAbs = /^(https?:|data:|blob:)/i.test(path)
      const isRoot = /^\//.test(path)
      const url = isImg
        ? (isAbs
            ? path
            : `${API_BASE_URL}${isRoot ? path : `/${path}`}`)
        : undefined
      return {
        id: `pay-detail-${idx}`,
        name: att.name,
        serverPath: att.path,
        uploadedPath: att.path,
        status: 'done',
        file: null,
        isImage: isImg,
        url,
      }
    })
  },
  { immediate: true }
)
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
const getAttIconClass = (att: { ext: string }) => {
  const e = (att.ext || '').toLowerCase()
  if (imageExts.includes(e)) return 'img'
  if (e === 'pdf') return 'pdf'
  if (e === 'docx' || e === 'doc') return 'docx'
  if (e === 'xls' || e === 'xlsx') return 'xls'
  return 'file'
}
const getAttIconText = (att: { ext: string }) => {
  const e = (att.ext || '').toUpperCase()
  if (imageExts.includes(e.toLowerCase())) return 'IMG'
  if (e === 'PDF') return 'PDF'
  if (e === 'DOCX' || e === 'DOC') return 'W'
  if (e === 'XLS' || e === 'XLSX') return 'XLS'
  return 'FILE'
}

// 与上传附件一致的预览逻辑：图片直接 showImagePreview，其余跳转到 /file-preview
const normalizeServerPath = (raw: string) => {
  if (!raw || typeof raw !== 'string') return ''
  try {
    return raw.replace(/\\/g, '/')
  } catch {
    return raw
  }
}

const fetchBlobUrlWithRefresh = async (filePath: string) => {
  const makeRequest = async () => {
    const response = await request(`${API_BASE_URL}/OA/file/download`, {
      method: 'GET',
      params: { path: filePath },
      responseType: 'blob',
    })
    return response
  }

  const resp = await makeRequest()
  const headers = (resp as any)?.headers || {}
  const contentType = headers['content-type'] || headers['Content-Type'] || ''
  const blobData = (resp as any)?.data ? (resp as any).data : resp

  if (String(contentType).toLowerCase().includes('application/json')) {
    try {
      const text = await (blobData as Blob).text()
      const json = JSON.parse(text)
      const msg = json?.msg || json?.message || ''
      if (json?.code === 401 || /token/i.test(msg)) {
        try {
          const refreshResp = await refreshTokenApi()
          const newToken = refreshResp?.data?.accessToken
          if (newToken) {
            isolatedStorage.setItem('accessToken', newToken)
            const retried = await makeRequest()
            const retriedBlobData = (retried as any)?.data ? (retried as any).data : retried
            const blob = retriedBlobData instanceof Blob ? retriedBlobData : new Blob([retriedBlobData])
            return window.URL.createObjectURL(blob)
          }
          throw new Error('刷新token失败，请重新登录')
        } catch (e) {
          throw new Error(json?.msg || '登录已过期，请重新登录')
        }
      }
      const blob = new Blob([text], { type: 'text/plain' })
      return window.URL.createObjectURL(blob)
    } catch (e) {
      const blob = blobData instanceof Blob ? blobData : new Blob([blobData as any])
      return window.URL.createObjectURL(blob)
    }
  }

  const blob = blobData instanceof Blob ? blobData : new Blob([blobData as any])
  return window.URL.createObjectURL(blob)
}

const previewAttachment = async (att: { path: string; name: string; ext: string }) => {
  try {
    const path = normalizeServerPath(att.path)
    const ext = (att.ext || '').toLowerCase()
    const isImage = imageExts.includes(ext)

    if (isImage) {
      const blobUrl = await fetchBlobUrlWithRefresh(path)
      if (!blobUrl) {
        showToast('预览地址获取失败')
        return
      }
      showImagePreview([blobUrl])
      return
    }

    // 非图片：跳转到统一的文件预览页
    router.push({
      path: '/file-preview',
      query: {
        path: encodeURIComponent(path),
        name: encodeURIComponent(att.name || '')
      }
    })
  } catch (e: any) {
    console.error('附件预览失败:', e)
    const msg = e?.message || ''
    if (msg.includes('登录') || /401/.test(msg) || /token/.test(msg)) {
      showToast(msg.includes('登录') ? msg : '登录已过期，请重新登录')
      const currentPath = window.location.hash.slice(1)
      setTimeout(() => {
        window.location.href = `/#/login?redirect=${encodeURIComponent(currentPath || '/')}`
      }, 1200)
    } else {
      showToast('预览失败，请稍后重试')
    }
  }
}



// 显示弹窗的方法
const showRevokeDialog = () => {
  currentAction.value = 'revoke'
  dialogConfig.value = {
    title: '撤销申请',
    message: '确认要撤销此申请吗？',
    confirmText: '确认撤销',
    placeholder: '请输入撤销原因'
  }
  remark.value = ''
  showConfirmDialog.value = true
}

const showRejectDialog = () => {
  currentAction.value = 'reject'
  dialogConfig.value = {
    title: '拒绝申请',
    message: '确认要拒绝此申请吗？',
    confirmText: '确认拒绝',
    placeholder: '请输入拒绝原因'
  }
  remark.value = ''
  showConfirmDialog.value = true
}

const showApproveDialog = () => {
  currentAction.value = 'approve'
  dialogConfig.value = {
    title: '同意申请',
    message: '确认要同意此申请吗？',
    confirmText: '确认同意',
    placeholder: '请输入同意原因'
  }
  remark.value = ''
  showConfirmDialog.value = true
}

// 通用取消操作
const handleCancel = () => {
  showConfirmDialog.value = false
  remark.value = ''
}

// 通用确认操作
const handleConfirm = async () => {
  if (!remark.value.trim()) {
    showToast('请输入原因')
    return
  }

  switch (currentAction.value) {
    case 'revoke':
      await handleRevoke()
      break
    case 'reject':
      await handleReject()
      break
    case 'approve':
      await handleApprove()
      break
  }
}

// 按钮事件处理
const handleRevoke = async () => {
   try {
    revokeLoading.value = true
    showConfirmDialog.value = false
    
    const result = await revokeContract({
      id: detailData.id,
      type: "3",//1、合同、2、报销、3、付款
      remark: remark.value.trim(),
    })
    
     if (result.code === 0) {
      showToast("撤销成功");
      remark.value = "";
      
      const fromApprovals = route.query.from === 'approvals'
      const fromAdd = route.query.from === 'add'
      
      if (fromApprovals || fromAdd) {
        router.push('/approvals')
      } else {
        router.push('/home')
      }
    } else {
      showToast(result.msg || "撤销失败");
    }
  } catch (error) {
    showToast("撤销失败，请重试");
    console.error("撤销操作失败:", error);
  } finally {
    revokeLoading.value = false;
  }
}

const handleReject = async () => {
  try {
    rejectLoading.value = true
    showConfirmDialog.value = false
    console.log(detailData,'detailData');
    const result = await dealPayApi(detailData.id, false, remark.value, detailData.payObject || '')
    
    if (result.code === 0) {
      showToast('拒绝成功')
      remark.value = ''
      
      const fromApprovals = route.query.from === 'approvals'
      const fromAdd = route.query.from === 'add'
      
      if (fromApprovals || fromAdd) {
        router.push('/approvals')
      } else {
        router.push('/home')
      }
    } else {
      showToast(result.msg || '拒绝失败')
    }
  } catch (error) {
    showToast('拒绝失败，请重试')
    console.error('拒绝操作失败:', error)
  } finally {
    rejectLoading.value = false
  }
}

const handleApprove = async () => {
  try {
    approveLoading.value = true
    showConfirmDialog.value = false
    
    const result = await dealPayApi(detailData.id, true, remark.value, detailData.payObject || '')
    
    if (result.code === 0) {
      showToast('同意成功')
      remark.value = ''
      
      const fromApprovals = route.query.from === 'approvals'
      const fromAdd = route.query.from === 'add'
      
      if (fromApprovals || fromAdd) {
        router.push('/approvals')
      } else {
        router.push('/home')
      }
    } else {
      showToast(result.msg || '同意失败')
    }
  } catch (error) {
    showToast('同意失败，请重试')
    console.error('同意操作失败:', error)
  } finally {
    approveLoading.value = false
  }
}

// 获取当前登录用户ID
const getCurrentUserId = () => {
  try {
    const userInfo = isolatedStorage.getUserInfo()
    if (userInfo) {
      return userInfo.id || null
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
  return null
}

// 判断是否显示撤销按钮
const shouldShowRevokeButton = () => {
  console.log(currentUserId.value, 'currentUserId.value', detailData.createId)
  return (
    currentUserId.value !== null && currentUserId.value === detailData.createId
  )
}

// 判断当前用户是否为当前审批人
const isCurrentApprover = () => {
  if (currentUserId.value === null || !detailData.nowApprover) {
    return false
  }

  // 检查当前用户ID是否与nowApprover匹配
  if (currentUserId.value !== detailData.nowApprover) {
    return false
  }

  // 检查nowApprover是否在审批人列表中
  const approvers = [
    detailData.firstApprover,
    detailData.secondApprover,
    detailData.thirdApprover,
  ]
  return (
    approvers.includes(detailData.nowApprover) && detailData.nowApprover !== -1
  )
}

// 判断是否显示审批按钮（拒绝、同意）
const shouldShowApprovalButtons = () => {
  return detailData.nowState === 0 && isCurrentApprover()
}

// 页面挂载时获取数据
onMounted(() => {
  // 获取当前登录用户ID
  currentUserId.value = getCurrentUserId()
  fetchDetailData()
})

// 导出响应式变量和方法供模板使用
defineExpose({
  loading,
  revokeLoading,
  approveLoading,
  rejectLoading,
  showConfirmDialog,
  dialogConfig,
  remark,
  currentAction,
  detailData,
  getStatusIcon,
  getStatusText,
  getStatusClass,
  getHandleText,
  getPayObjectName,
  goBack,
  fetchDetailData,

  showRevokeDialog,
  showRejectDialog,
  showApproveDialog,
  handleCancel,
  handleConfirm,
  handleRevoke,
  handleReject,
  handleApprove,
  shouldShowRevokeButton,
  isCurrentApprover,
  shouldShowApprovalButtons
})
</script>

<style lang="scss" scoped>
@import url('./style/pay.scss');

// 弹窗样式
.dialog-content {
  padding: 16px;
  
  .dialog-text {
    margin-bottom: 16px;
    font-size: 14px;
    color: #323233;
    text-align: center;
  }
  
  :deep(.van-field) {
    padding: 0;
    
    .van-field__control {
      min-height: 80px;
      padding: 12px;
      border: 1px solid #ebedf0;
      border-radius: 6px;
      font-size: 14px;
      line-height: 1.4;
      resize: none;
      
      &:focus {
        border-color: #1989fa;
      }
    }
    
    .van-field__word-limit {
      margin-top: 8px;
      text-align: right;
      font-size: 12px;
      color: #969799;
    }
  }
}

/* 附件列表样式 */
.attachments-list {
  margin-top: 8px;
}
.att-row {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f2f3f5;
}
.att-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 12px;
  box-sizing: border-box;
  background: #eef3fb;
  color: #1565c0;
}
.att-icon.img {
  background: #e8f5e9;
  color: #2e7d32;
}
.att-icon.pdf {
  background: #ffebee;
  color: #c62828;
}
.att-icon.docx {
  background: #e3f2fd;
  color: #1565c0;
}
.att-icon.xls {
  background: #e8f5e9;
  color: #1b5e20;
}
.att-name {
  flex: 1;
  font-size: 14px;
  color: #323233;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.empty-tip {
  padding: 12px 16px;
  color: #969799;
  font-size: 12px;
}
</style>